/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package xiaofei.library.hermestest.slice;

import xiaofei.library.hermes.Hermes;
import xiaofei.library.hermes.stub.StubCallback;
import xiaofei.library.hermestest.FileUtils;
import xiaofei.library.hermestest.ResourceTable;
import xiaofei.library.hermestest.Utils;
import xiaofei.library.hermestest.service.FilePathSecondServiceAbility;
import xiaofei.library.hermestest.service.FilePathThreeServiceAbility;
import xiaofei.library.hermestest.service.ProcessAbility;
import xiaofei.library.hermestest.service.ProgressServiceAbility;
import xiaofei.library.hermestest.service.UserProcessSecondServiceAbility;
import xiaofei.library.hermestest.service.UserServiceAbility;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ProgressBar;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

import java.util.Timer;
import java.util.TimerTask;

/**
 * demo功能界面
 *
 * @author:Hexy
 * @since 2021-04-14
 */
public class DemoAbilitySlice extends AbilitySlice {
    private static final int EVENT_MESSAGE_NORMAL = 1;
    private static final int EVENT_MESSAGE_THIRD = 2;
    private static final int NUMBER10 = 10;
    private static final int NUMBER100 = 100;
    private static final int NUMBER1000 = 1000;
    private ProgressBar mProgressBar;
    private ProgressBar mProgressThirdBar;
    private MyEventHandler myHandler;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_demo);

        initView();
        setListener();
        clickListener();

        EventRunner runner = EventRunner.current();
        myHandler = new MyEventHandler(runner);
    }

    /**
     * 初始化界面
     */
    private void initView() {
        mProgressBar = (ProgressBar) findComponentById(ResourceTable.Id_progress_bar);
        mProgressThirdBar = (ProgressBar) findComponentById(ResourceTable.Id_progressthird_bar);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    /**
     * 点击监听事件
     */
    public void setListener() {
        findComponentById(ResourceTable.Id_btn_download_second_process).setClickedListener(component -> {
            Hermes.handlePregress(ProgressServiceAbility.class.getName(), this,
                    (StubCallback<String>) value -> {
                        final Timer timer = new Timer();
                        timer.schedule(new TimerTask() {
                            int value = 0;

                            @Override
                            public void run() {
                                value += NUMBER10;
                                if (value > NUMBER100) {
                                    value = NUMBER100;
                                }
                                InnerEvent normalInnerEvent = InnerEvent.get(EVENT_MESSAGE_NORMAL, value, null);
                                myHandler.sendEvent(normalInnerEvent, 0, EventHandler.Priority.IMMEDIATE);
                                if (value == NUMBER100) {
                                    timer.cancel();
                                }
                            }
                        }, 0, NUMBER1000);
                    });
        });

        findComponentById(ResourceTable.Id_btn_download_third_process).setClickedListener(component -> {
            Hermes.handleProcess(ProcessAbility.class.getName(), this,
                    (StubCallback<String>) value -> {
                        final Timer timer = new Timer();
                        timer.schedule(new TimerTask() {
                            int value = 0;

                            @Override
                            public void run() {
                                value += NUMBER10;
                                if (value > NUMBER100) {
                                    value = NUMBER100;
                                }
                                InnerEvent normalInnerEvent = InnerEvent.get(EVENT_MESSAGE_THIRD, value, null);
                                myHandler.sendEvent(normalInnerEvent, 0, EventHandler.Priority.IMMEDIATE);
                                if (value == NUMBER100) {
                                    timer.cancel();
                                }
                            }
                        }, 0, NUMBER1000);
                    });
        });
    }

    /**
     * 点击事件
     */
    public void clickListener() {
        findComponentById(ResourceTable.Id_btn_getuser_second_process).setClickedListener(component -> {
            Hermes.handleUser(UserServiceAbility.class.getName(), this,
                    (StubCallback<String>) value -> {
                        Utils.showDialog(getContext(), value);
                    });
        });

        findComponentById(ResourceTable.Id_btn_getuser_third_process).setClickedListener(component -> {
            Hermes.handleUserProcessThree(UserProcessSecondServiceAbility.class.getName(), this,
                    (StubCallback<String>) value -> {
                        Utils.showDialog(getContext(), value);
                    });
        });

        findComponentById(ResourceTable.Id_btn_filepath_second_process).setClickedListener(component -> {
            Hermes.handlePregress(FilePathSecondServiceAbility.class.getName(), this,
                    (StubCallback<String>) value -> {
                        Utils.showDialog(getContext(), FileUtils.getExternalCacheDir(this));
                    });
        });

        findComponentById(ResourceTable.Id_btn_filepath_third_process).setClickedListener(component -> {
            Hermes.handlePregress(FilePathThreeServiceAbility.class.getName(), this,
                    (StubCallback<String>) value -> {
                        Utils.showDialog(getContext(), FileUtils.getExternalCacheDir(this));
                    });
        });
    }

    /**
     * 更新UI的 Handler类
     *
     * @author:Hexy
     * @since 2021-04-14
     */
    private class MyEventHandler extends EventHandler {
        private MyEventHandler(EventRunner runner) {
            super(runner);
        }

        // 重写实现processEvent方法
        @Override
        public void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event == null) {
                return;
            }
            int eventId = event.eventId;
            switch (eventId) {
                case EVENT_MESSAGE_NORMAL:
                    // 待执行的操作，由开发者定义
                    int value = (int) event.param;
                    mProgressBar.setProgressValue(value);
                    mProgressBar.setProgressHintText(value + "%");
                    break;
                case EVENT_MESSAGE_THIRD:
                    // 待执行的操作，由开发者定义
                    int valueThird = (int) event.param;
                    mProgressThirdBar.setProgressValue(valueThird);
                    mProgressThirdBar.setProgressHintText(valueThird + "%");
                    break;
                default:
                    break;
            }
        }
    }
}